package org.linlinjava.litemall.admin.job;

import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.admin.beans.Constants;
import org.linlinjava.litemall.admin.beans.enums.AdminOrderStatusEnum;
import org.linlinjava.litemall.admin.erp.client.DepotClient;
import org.linlinjava.litemall.admin.erp.rq.PurchaseDepotItem;
import org.linlinjava.litemall.admin.erp.rq.PurchaseInfo;
import org.linlinjava.litemall.admin.erp.rq.PurchaseRQ;
import org.linlinjava.litemall.admin.task.ScheduledCronTaskRegistrar;
import org.linlinjava.litemall.db.domain.LitemallAdminOrder;
import org.linlinjava.litemall.db.domain.LitemallAdminOrderMerchandise;
import org.linlinjava.litemall.db.domain.LitemallMerchandise;
import org.linlinjava.litemall.db.domain.LitemallMerchandiseLog;
import org.linlinjava.litemall.db.domain.LitemallShop;
import org.linlinjava.litemall.db.service.LitemallAdminOrderMerchandiseService;
import org.linlinjava.litemall.db.service.LitemallAdminOrderService;
import org.linlinjava.litemall.db.service.LitemallMerchandiseLogService;
import org.linlinjava.litemall.db.service.LitemallMerchandiseService;
import org.linlinjava.litemall.db.service.LitemallShopService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 管理订单工作
 * 订单状态
 *
 * @author yliyun
 * @date 2022/09/14
 */
@Component
public class AdminOrderJob implements Job {
    /**
     * 日志记录器
     */
    private final Log logger = LogFactory.getLog(AdminOrderJob.class);

    /**
     * litemall管理订单服务
     */
    @Autowired
    private LitemallAdminOrderService litemallAdminOrderService;
    /**
     * litemall管理订单商品服务
     */
    @Autowired
    private LitemallAdminOrderMerchandiseService litemallAdminOrderMerchandiseService;
    /**
     * litemall商品服务
     */
    @Autowired
    private LitemallMerchandiseService litemallMerchandiseService;
    /**
     * 商品日志服务
     */
    @Autowired
    private LitemallMerchandiseLogService merchandiseLogService;
    /**
     * 店服务
     */
    @Autowired
    private LitemallShopService shopService;
    /**
     * 得宝客户端
     */
    @Autowired
    private DepotClient depotClient;
    /**
     * 得宝购买url
     */
    @Value("${erp.depot.purchase.url}")
    private String depotPurchaseUrl ;

    @Autowired
    private ScheduledCronTaskRegistrar scheduledCronTaskRegistrar;


    /**
     * TODO erp采购
     * <p>
     * 定时检查等待发货的订单情况，向erp发起采购
     * <p>
     */
    //@Scheduled(cron = "30 10 * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void erpPurchase() {
        logger.info("系统开启任务检查等待发货的订单向erp发起采购");

        List<LitemallAdminOrder> orders = litemallAdminOrderService.queryByOrderStatus(AdminOrderStatusEnum.P_9.getCode().byteValue());
        for (LitemallAdminOrder order : orders) {
        	 PurchaseRQ rq = new PurchaseRQ();
        	 //设置采购的基本信息
             PurchaseInfo info = new PurchaseInfo();
             info.setDefaultNumber(order.getOrderSn());
             LitemallShop shop = shopService.findById(order.getShopId());
             String erpCode = shop.getErpCode();
             if(StringUtils.isBlank(erpCode)) {
            	 logger.info("店铺["+ shop.getName() + "]未绑定erp店铺编码，不可发起采购");
            	 continue;
             }
             info.setOrganCode(erpCode);;
             info.setRemark(order.getOrderRemark());
             info.setTotalPrice(order.getActualPrice());
             rq.setInfo(JSONObject.toJSONString(info));

             List<LitemallAdminOrderMerchandise> litemallAdminOrderMerchandises = litemallAdminOrderMerchandiseService.querybyAdminOrderId(order.getId());
             if(litemallAdminOrderMerchandises != null){
                 //设置需要采购的商品
                 List<PurchaseDepotItem> collect = litemallAdminOrderMerchandises.stream().map(item -> {
                 	Integer merchandiseId = item.getMerchandiseId();
                 	LitemallMerchandise litemallMerchandise = litemallMerchandiseService.findById(merchandiseId);
                     PurchaseDepotItem depot = new PurchaseDepotItem();
                     depot.setBarCode(litemallMerchandise.getMerchandiseSn());
                     depot.setUnit(litemallMerchandise.getUnit());
                     depot.setOperNumber(String.valueOf(item.getNumber()));
                     return depot;
                 }).collect(Collectors.toList());
                 rq.setInserted(JSONArray.toJSONString(collect));
             }

            try {
            	//得到订单编号保存到数据库
                String number = depotClient.addDepotHeadAndDetail(rq, depotPurchaseUrl);

                if(StringUtils.isNotBlank(number)) {
                	 //保存单据编号，修改订单状态
                    LitemallAdminOrder update = new LitemallAdminOrder();
                    update.setId(order.getId());
                    update.setErpOrderSn(number);
                    update.setOrderStatus(AdminOrderStatusEnum.P_3.getCode().byteValue());
                    litemallAdminOrderService.update(update);

                    /**
                     * 保存日志
                     */
                    LitemallMerchandiseLog merchandiseLog = new LitemallMerchandiseLog();
                    merchandiseLog.setAdminOrderId(order.getId());
                    merchandiseLog.setOrderSn(order.getOrderSn());
                    merchandiseLog.setContent(Constants.ERP_PURCHASE);
                    merchandiseLog.setShopId(order.getShopId());
                    merchandiseLogService.insert(merchandiseLog);
                }

			} catch (Exception e) {
				// TODO: handle exception
				logger.info("系统向erp发起采购失败，失败订单id为："+order.getId());
			}

		}

    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        this.erpPurchase();
        scheduledCronTaskRegistrar.scheduleJobLog(jobExecutionContext);
    }
}
